{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np  \n",
    "\n",
    "def cmma_vectorized(values, lookback):  \n",
    "    # 计算移动平均值的数组  \n",
    "    ma = np.convolve(values, np.ones((lookback,)) / lookback, mode='valid')  \n",
    "      \n",
    "    # 初始化结果数组，并填充NaN值直到移动平均值数组的长度  \n",
    "    out = np.empty(len(values))  \n",
    "    out[:len(ma)] = np.nan  \n",
    "      \n",
    "    # 将移动平均值从收盘价中减去  \n",
    "    out[lookback-1:] = values[lookback-1:] - ma  \n",
    "      \n",
    "    return out  \n",
    "  \n",
    "def cmma(bar_data, lookback):  \n",
    "    # 假设bar_data是一个包含收盘价的NumPy数组  \n",
    "    return cmma_vectorized(bar_data, lookback)  \n",
    "  \n",
    "# 示例使用  \n",
    "close_prices = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18])  # 收盘价示例  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([nan, nan,  1.,  1.,  1.,  1.,  1.,  1.,  1.])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cmma(close_prices, lookback=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "close_prices = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 16, 15, 14, 10])  # 收盘价示例  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([        nan,         nan,  1.        ,  1.        ,  1.        ,\n",
       "        1.        ,  1.        ,  1.        ,  1.        , -1.        ,\n",
       "       -1.33333333, -1.        , -3.        ])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cmma(close_prices, lookback=3)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
